<?php
declare(strict_types=1);

namespace app\controller\user;

use app\BaseController;
use app\model\{User, UserBalanceFlow, UserWithdrawRecord, RechargeAmount};
use app\service\{WechatService, AlipayService};
use think\facade\{Db, Log};
use think\Request;

class UserBalanceController extends BaseController
{
    /**
     * 获取余额
     */
    public function getBalance(Request $request)
    {
        try {
            $user = User::find($request->user_id);
            return json([
                'code' => 0,
                'msg' => '获取成功',
                'data' => [
                    'balance' => $user->balance,
                    'frozen_balance' => $user->frozen_balance ?? 0
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('获取余额失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 创建充值订单
     */
    public function createRecharge(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $user = $request->user;
            
            // 验证金额
            if (empty($params['amount']) || $params['amount'] <= 0) {
                return json(['code' => 1, 'msg' => '充值金额必须大于0']);
            }
            
            // 生成订单号
            $order_no = 'UR' . date('YmdHis') . mt_rand(1000, 9999);
            
            // 创建充值记录
            $record = UserBalanceFlow::create([
                'merchant_id' => $user->merchant_id,
                'user_id' => $user->id,
                'order_no' => $order_no,
                'type' => 1, // 充值
                'amount' => $params['amount'],
                'payment_method' => $params['payment_method'],
                'status' => 0, // 未支付
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            // 根据支付方式返回支付参数
            $pay_data = [];
            switch ($params['payment_method']) {
                case 1: // 微信支付
                    $wechatService = new WechatService($user->merchant_id);
                    $pay_data = $wechatService->createUserRechargeOrder($record, $user->openid);
                    break;
                    
                case 2: // 支付宝支付
                    $alipayService = new AlipayService($user->merchant_id);
                    $pay_data = $alipayService->createUserRechargeOrder($record);
                    break;
                    
                default:
                    throw new \Exception('不支持的支付方式');
            }
            
            Db::commit();
            return json([
                'code' => 0,
                'msg' => '创建成功',
                'data' => [
                    'order_no' => $order_no,
                    'amount' => $params['amount'],
                    'pay_params' => $pay_data
                ]
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('创建充值订单失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 申请提现
     */
    public function withdraw(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $user = $request->user;
            
            // 检查用户状态
            if ($user->status == 1) {
                return json(['code' => 1, 'msg' => '账号已被限制使用']);
            }
            
            // 验证金额
            if (empty($params['amount']) || $params['amount'] <= 0) {
                return json(['code' => 1, 'msg' => '提现金额必须大于0']);
            }
            
            // 验证余额
            if ($user->balance < $params['amount']) {
                return json(['code' => 1, 'msg' => '余额不足']);
            }
            
            // 生成提现单号
            $withdraw_no = 'UW' . date('YmdHis') . mt_rand(1000, 9999);
            
            // 创建提现记录
            UserWithdrawRecord::create([
                'merchant_id' => $user->merchant_id,
                'user_id' => $user->id,
                'withdraw_no' => $withdraw_no,
                'withdraw_amount' => $params['amount'],
                'withdraw_fee' => 0, // 手续费,可从配置读取
                'withdraw_name' => $params['withdraw_name'],
                'withdraw_account' => $params['withdraw_account'],
                'withdraw_account_type' => $params['withdraw_account_type'],
                'status' => 0, // 待审核
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            // 冻结余额
            $user->save([
                'balance' => Db::raw('balance-' . $params['amount']),
                'frozen_balance' => Db::raw('frozen_balance+' . $params['amount'])
            ]);
            
            // 记录资金流水
            UserBalanceFlow::create([
                'merchant_id' => $user->merchant_id,
                'user_id' => $user->id,
                'type' => 2, // 提现
                'amount' => -$params['amount'],
                'order_no' => $withdraw_no,
                'status' => 0, // 待审核
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return json(['code' => 0, 'msg' => '申请成功,请等待审核']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('申请提现失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取余额流水
     */
    public function flowList(Request $request)
    {
        try {
            $params = $request->get();
            $user = $request->user;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [
                ['user_id', '=', $user->id],
                ['merchant_id', '=', $user->merchant_id]
            ];
            
            // 流水类型筛选
            if (isset($params['type'])) {
                $where[] = ['type', '=', $params['type']];
            }
            
            // 时间范围筛选
            if (!empty($params['start_time'])) {
                $where[] = ['create_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['create_time', '<=', $params['end_time']];
            }
            
            $list = UserBalanceFlow::where($where)
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取余额流水失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取提现记录
     */
    public function withdrawList(Request $request)
    {
        try {
            $params = $request->get();
            $user = $request->user;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [
                ['user_id', '=', $user->id],
                ['merchant_id', '=', $user->merchant_id]
            ];
            
            // 状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            $list = UserWithdrawRecord::where($where)
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取提现记录失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 